package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.constants.WemediaConstants;
import com.heima.model.common.dtos.common.PageResponseResult;
import com.heima.model.common.dtos.common.ResponseResult;
import com.heima.model.common.dtos.wemedia.WmMaterialDto;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
* @author Fu319
* @description 针对表【wm_material(自媒体图文素材信息表)】的数据库操作Service实现
* @createDate 2025-04-02 14:33:26
*/
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    private static final Integer FILE_TYPE_IMAGE = 0;
    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    private FileStorageService fileStorageService;
    /**
     * 上传素材功能
     * @param file
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile file) {
        //检查参数
        if (file==null || file.getSize()==0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        String path=null;
        Integer type=FILE_TYPE_IMAGE;
        String originalFilename = file.getOriginalFilename();
        String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));
        if(!(postfix.equals(".jpg")||postfix.equals(".jpeg")||postfix.equals(".bmp")||postfix.equals(".png")||postfix.equals(".gif"))){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_IMAGE_FORMAT_ERROR);
        }
        //上传图片
        String fileName = UUID.randomUUID().toString().replace("-", "");

        try {
            InputStream in = file.getInputStream();
            path = fileStorageService.uploadImgFile("", fileName + postfix, in);
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
        //把图片上传到数据库中
        WmMaterial wmMaterial =WmMaterial
                .builder()
                .userId(WmThreadLocalUtil.getUser().getId())
                .type(type)
                .url(path)
                .createdTime(new Date())
                .isCollection(0)
                .build();
        wmMaterialMapper.insert(wmMaterial);
        //返回响应数据
        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 文章素材显示功能
     * @param wmMaterialDto
     * @return
     */
    @Override
    public ResponseResult listMaterials(WmMaterialDto wmMaterialDto) {
        if(wmMaterialDto.getIsCollection()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //设置查询条件
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        if(wmMaterialDto.getIsCollection().equals( WemediaConstants.COLLECT_MATERIAL)){
            wrapper.eq(WmMaterial::getIsCollection, wmMaterialDto.getIsCollection());
        }

        //定义分页数据
        if(wmMaterialDto.getPage()==null){
            wmMaterialDto.setPage(1);
        }
        IPage<WmMaterial> page = new Page(wmMaterialDto.getPage(),wmMaterialDto.getSize());
        //将分页信息和查询条件放在一起查询结果
        IPage<WmMaterial> wmMaterialIPage = wmMaterialMapper.selectPage(page,wrapper);
        //定义素材列表分页响应数据,并将分页信息和数据放入对象中
        PageResponseResult pageResponseResult=PageResponseResult.builder()
                .currentPage((int) wmMaterialIPage.getCurrent())
                .size((int) wmMaterialIPage.getSize())
                .total((int) wmMaterialIPage.getTotal())
                .build();
        pageResponseResult.setData(wmMaterialIPage.getRecords());
        pageResponseResult.setErrorMessage(String.valueOf(AppHttpCodeEnum.SUCCESS));
        return pageResponseResult;
    }

    /**
     * 删除文章素材
     * @param id
     * @return
     */
    @Override
    public ResponseResult delPicture(Integer id) {
        //先查询素材图文管理表中是否有该关联信息
        LambdaQueryWrapper<WmNewsMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmNewsMaterial::getMaterialId,id);
        List<WmNewsMaterial> wmNewsMaterials = wmNewsMaterialMapper.selectList(wrapper);
        //判断是否有关联信息
        if(CollectionUtils.isEmpty(wmNewsMaterials)){
            //如果没有则删除该素材信息
            WmMaterial wmMaterial = wmMaterialMapper.selectById(id);
            wmMaterialMapper.deleteById(id);
            //同时删除minio文件系统中的图片信息
            fileStorageService.delete(wmMaterial.getUrl());
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.WMMATERIAL_NEW_UNION_DELETE_FAILD);
    }
}




